import calculateAge from './calculateAge';

/**
 * 根据身份证判断是否成年人
 * @param {string} id 身份证号码
 */
export default function isAdult(id) {
    if (checkID(id) === false) return false;

    const birthday = calculateBirthdayFromId(id);
    const now = calculateCurrentDay();
    const age = calculateAge(birthday, now);
    return age >= 18;
}

/**
 * 校验身份证是否正确
 * @param {string} id 
 * @returns {boolean}
 */
function checkID(id) {
    if (!id) return false;
    if (typeof id !== 'string') return false;
    if (id.length !== 18) return false;

    const ID_REG = /^\d{18}|\d{17}x$/i;

    return ID_REG.test(id);
}

/**
 * 从身份证截取出生日期
 * @param {string} id 
 * @returns {number[]}
 */
function calculateBirthdayFromId(id) {
    const year = id.slice(6, 10);
    const month = id.slice(10, 12);
    const day = id.slice(12, 14);

    return [year, month, day].map(item => Number(item));
}

/**
 * 获取当前的日期
 */
function calculateCurrentDay() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const day = now.getDate();

    return [year, month, day];
}